package com.springcloud.eshop.datalink.controller;

import com.alibaba.fastjson.JSON;
import com.springcloud.eshop.datalink.service.EshopProductService;
import com.springcloud.eshop.entity.Product;
import com.springcloud.eshop.entity.ProductDto;
import com.springcloud.eshop.entity.ProductIntro;
import com.springcloud.eshop.entity.ProductProperty;
import com.springcloud.eshop.entity.ProductSpecification;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

/**
 * @Desc:
 * @Date: 2020-07-04
 * @Version:v1.0
 */
@RestController
public class DataLinkController {

    private Logger logger = LoggerFactory.getLogger(DataLinkController.class);

    @Autowired
    private EshopProductService eshopProductService;

    @Autowired
    private JedisPool jedisPool;


    @RequestMapping(value = "getProduct", method = RequestMethod.GET)
    @ResponseBody
    public ProductDto selectOneProduct(@RequestParam(value = "id") Long id) {
        logger.info("DataLinkController.selectOneProduct start, 调用数据直连服务，商品id : {}", id);
        // 读redis主集群
        String result = jedisPool.getResource().get("dim_product_" + id);
        if (StringUtils.isNotEmpty(result)) {
            return JSON.parseObject(result, ProductDto.class);
        }
        ProductDto productDto = new ProductDto();
        // 商品介绍信息
        Product product = eshopProductService.selectOneProduct(id);
        if (product != null) {
            productDto.setProduct(product);
        }

        // 商品介绍信息
        ProductIntro productIntro = eshopProductService.selectOneProductIntroByProductId(id);
        if (productIntro != null) {
            productDto.setProductIntro(productIntro);
        }

        // 商品规格
        ProductSpecification productSpecification = eshopProductService.selectOneProductSpecificationByProductId(id);
        if (productSpecification != null) {
            productDto.setProductSpecification(productSpecification);
        }

        // 商品属性
        ProductProperty productProperty = eshopProductService.selectOneProductPropertyByProductId(id);
        if (productProperty != null) {
            productDto.setProductProperty(productProperty);
        }
        logger.info("DataLinkController.selectOneProduct end, 调用数据直连服务，productDto : {}", JSON.toJSONString(productDto));
        return productDto;
    }
}
